import torch
import torch.nn as nn
torch.random.manual_seed(42)
# 创建一个线性层：输入特征数=3，输出特征数=2
linear_layer = nn.Linear(in_features=3, out_features=2)

# 查看参数
print("权重形状:", linear_layer.weight.shape)  # torch.Size([2, 3])
print("偏置形状:", linear_layer.bias.shape)    # torch.Size([2])

# 输入数据：batch_size=4, 特征数=3
input_tensor = torch.randn(4, 3)
print("输入形状:", input_tensor.shape)  # torch.Size([4, 3])
print(input_tensor)

# 前向传播
output = linear_layer(input_tensor)
print("输出形状:", output.shape)  # torch.Size([4, 2])


# 手动实现线性变换
def manual_linear(input_tensor, weight, bias):
    # input_tensor: [batch_size, in_features]
    # weight: [out_features, in_features]
    # bias: [out_features]

    # 矩阵乘法: input × weight^T
    output = torch.matmul(input_tensor, weight.t())
    # 加上偏置
    output += bias
    return output


# 使用相同参数进行验证
manual_output = manual_linear(input_tensor, linear_layer.weight, linear_layer.bias)
auto_output = linear_layer(input_tensor)
print(auto_output)

print("结果是否一致:", torch.allclose(manual_output, auto_output))  # True